package com.comunity_cloud.client.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;

import javax.swing.UIManager;

import org.apache.http.auth.AuthenticationException;

import com.comunity_cloud.client.model.CommunityFile;
import com.comunity_cloud.client.model.CommunityFile.State;
import com.comunity_cloud.client.model.Configuration;
import com.comunity_cloud.client.model.MainModel2;
import com.comunity_cloud.client.model.fetch_file.FetchFilesClient;
import com.comunity_cloud.client.model.fetch_file.FetchFilesClient.FetchFileListener;
import com.comunity_cloud.client.model.upload_file.UploadFilesManager;
import com.comunity_cloud.client.view2.LoginFrame;
import com.comunity_cloud.client.view2.MainView;
import com.comunity_cloud.client.view2.ProgressDialog;
import com.comunity_cloud.exceptions.ChunkUnavailableException;
import com.comunity_cloud.rest.RestClient;
import com.user_hosted_storage.dto.ClientDTO;
import com.user_hosted_storage.dto.CommunityDTO;

public class MainController2 {

	private LoginFrame loginFrame;
	private MainModel2 mainModel;
	private MainView mainView;

	private static MainController2 instance;
	
	private MainController2() {
		loginFrame = new LoginFrame();
		loginFrame.setController(this);
		
		mainModel = MainModel2.getInstance();
		
		loginFrame.setVisible(true);
	}
	
	public static MainController2 getInstance() {
		return instance;
	}
	
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {}
		instance = new MainController2();
	}

	public void login(String userName, String password) {
		RestClient.setCachedAuth(userName, password);
		new Thread(){
			public void run() {
				try {
					loginFrame.enableForm(false);
					mainModel.loginWithHost();
					showMainView();
					loginFrame.setVisible(false);
					mainView.initCommunities();
					
				} catch (AuthenticationException e) {
					loginFrame.showError("Invalid user name or password");
					loginFrame.enableForm(true);
				} catch (Exception e) {
					e.printStackTrace();
					loginFrame.showError("Connection error");
					loginFrame.enableForm(true);
				} 
			}
		}.start();
	}

	protected void showMainView() {
		mainView = new MainView(this);
		mainView.setVisible(true);		
	}

	public Collection<CommunityDTO> getMyCommunities() {
		
		return mainModel.getCommunities();
	}

	public void filesDropped(final File[] files, final CommunityDTO communityDTO) {
		

			ProgressDialog.getInstance().showDialog();
			
			
			new Thread(){
				public void run() {
					try {
						UploadFilesManager uploadManager = MainModel2.getInstance().getUploadFilesManager();
						
						long sumSize = 0;
						for (File file : files) {
							sumSize += file.length();
						}
						
						for (File file : files) {
							String targetPath = Configuration.getInstance().communityPath+communityDTO.getName()+"/"+file.getName();							
							File targetFile = new File(targetPath);
							ProgressDialog.getInstance().setProgressText("Queuing file: "+file.getName());
							Files.copy(file.toPath(), targetFile.toPath());
							ProgressDialog.getInstance().increaseProgress((int) (((double)file.length()/sumSize)*100));
							
						}
						synchronized (uploadManager) {
							uploadManager.notifyAll();
						}
						ProgressDialog.getInstance().hideDialog();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
			
			
		
	}

	public ClientDTO getClient() {
		return mainModel.getClientDTO();
	}
	
	public void openFile(final CommunityFile file) {
		final FetchFilesClient fetchFilesManager = mainModel.getFetchFilesClient();
		final String tmpDir = Configuration.getInstance().tempDir+mainModel.getClientDTO().getId();
			
		new File(tmpDir).mkdirs();
		final File localFile = new File(tmpDir+File.separator+file.getPath().replace(" ", "_"));
		if(localFile.exists()) {
				
			try {
				openFile(localFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
			
		ProgressDialog.getInstance().showDialog();
		ProgressDialog.getInstance().setProgressText("Opening file");
		
		try {
			fetchFilesManager.fetchFile(file, tmpDir, new FetchFileListener() {
							
							@Override
							public void fetchProgress(int progress) {
								
								ProgressDialog.getInstance().setProgress(progress);
							}

							@Override
							public void error() {
								// TODO Auto-generated method stub
								
							}

							@Override
							public void finished() {
								try {
									ProgressDialog.getInstance().hideDialog();
									openFile(localFile);
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						});
						
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ChunkUnavailableException e) {
			e.printStackTrace();
		}
				

		
	}

	private void openFile(File localFile) throws IOException {
		String command = "cmd /c start "+localFile.getAbsolutePath();
		System.out.println(command);
		Runtime.getRuntime().exec(command);
	}

	public void deleteFile(CommunityFile row) {
		row.setState(State.DELETED);
	}
	
	public MainView getMainView() {
		return mainView;
	}
}
